package com.vitas.coin.ui.act;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BarUtils;
import com.snap.base.util.BaseUtil;
import com.snap.common.main.BaseAct;
import com.snap.util.edge.EdgePaddingMarginKt;
import com.vitas.coin.callback.DeleteListener;
import com.vitas.coin.data.bean.ChildrenVoiceBean;
import com.vitas.coin.data.bean.DownloadedBean;
import com.vitas.coin.data.event.FavorEvent;
import com.vitas.coin.data.event.PlayEvent;
import com.vitas.coin.databinding.ActivityPlaylistDetailBinding;
import com.vitas.coin.db.DBListener;
import com.vitas.coin.db.DownDao;
import com.vitas.coin.db.PlayDao;
import com.vitas.coin.resp.CollectDaoResp;
import com.vitas.coin.task.SilentTask;
import com.vitas.coin.task.TaskEngine;
import com.vitas.coin.ui.adapter.ListDetailAdapter;
import com.vitas.coin.util.Audio;
import com.vitas.coin.util.Utils;
import com.vitas.coin.util.drag.DragSwipeCallback;

import java.util.ArrayList;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;
import kotlin.jvm.functions.Function2;

public class FavorListAct extends BaseAct implements DeleteListener {

    ActivityPlaylistDetailBinding binding;
    ListDetailAdapter adapter;
    ArrayList<ChildrenVoiceBean> list;
    Handler h = new Handler();
    int from = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityPlaylistDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        EdgePaddingMarginKt.paddingVerticalSystemWindowInsets(binding.getRoot());
        BarUtils.transparentStatusBar(this);
        BarUtils.setStatusBarLightMode(this, true);

        binding.ivBack.setOnClickListener(v -> finish());
        from = getIntent().getIntExtra("from", 0);
        binding.rvList.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        adapter = new ListDetailAdapter(this, this, list);
        binding.rvList.setAdapter(adapter);

        ItemTouchHelper.Callback callback = new DragSwipeCallback(adapter);
        ItemTouchHelper touchHelper = new ItemTouchHelper(callback);
        touchHelper.attachToRecyclerView(binding.rvList);

        binding.menu.setVisibility(View.GONE);
        binding.tvPlayAll.setOnClickListener(v -> {
            if (list == null || list.isEmpty()) {
                return;
            }
            Intent i = new Intent(this, PlayAct.class);
            i.putExtra("index", 0);
            i.putParcelableArrayListExtra("list", list);
            startActivity(i);
        });

        if (from == 0) {
            binding.title.setText("我的喜欢");
            list = getIntent().getParcelableArrayListExtra("list");
            setData(list);
        } else if (from == 1) {
            binding.title.setText("最近播放");
        } else if (from == 2) {
            binding.title.setText("常听铃声");
        }
        initObserve();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (from == 1) {
            new PlayDao().getAll(new DBListener() {
                @Override
                public void onResult(boolean bo, String msg, Object result) {
                    h.post(() -> setData((ArrayList) result));
                }
            });
        } else if (from == 2) {
            new PlayDao().getAlways(new DBListener() {
                @Override
                public void onResult(boolean bo, String msg, Object result) {
                    h.post(() -> setData((ArrayList) result));
                }
            });
        }
    }

    private void setData(ArrayList list) {
        this.list = list;
        if (list.isEmpty()) {
            binding.empty.setVisibility(View.VISIBLE);
        } else {
            binding.empty.setVisibility(View.GONE);
        }
        adapter.setList(list);
    }

    private void initObserve() {
        BaseUtil.INSTANCE.observeForever(FavorEvent.class, new Function1<FavorEvent, Unit>() {
            @Override
            public Unit invoke(FavorEvent favorEvent) {
                if (from != 0) {
                    return null;
                }
                for (ChildrenVoiceBean item : list) {
                    if (item.getId() == favorEvent.getId()) {
                        int i = list.indexOf(item);
                        list.remove(item);
                        adapter.notifyItemRemoved(i);
                        break;
                    }
                }
                return null;
            }
        });
    }

    public void onItemDelete(ChildrenVoiceBean bean) {
        if (list.isEmpty()) {
            binding.empty.setVisibility(View.VISIBLE);
        }
        cancel(bean);
    }

    @Override
    public void onItemEdit(ChildrenVoiceBean bean) {
        Audio.editAudio(bean, this);
    }

    private void cancel(ChildrenVoiceBean musicObj) {
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                if (from == 0) {
                    musicObj.setCollect(false);
                    CollectDaoResp.INSTANCE.delete(musicObj);
                    h.post(() -> {
                        BaseUtil.INSTANCE.postEvent(new FavorEvent(musicObj.getId(), false));
                    });
                } else if (from == 1) {
                    new PlayDao().delete(musicObj);
                    h.post(() -> {
                        BaseUtil.INSTANCE.postEvent(new PlayEvent());
                    });
                } else if (from == 2) {
                    new PlayDao().resetNum(musicObj);
                    h.post(() -> {
                        BaseUtil.INSTANCE.postEvent(new PlayEvent());
                    });
                }
            }
        });
    }
}
